<!--
 * @Date: 2024-11-11 15:49:36
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2024-11-14 10:17:17
 * @Description: 下拉控件的数据集以及替换字段配置（已弃用替换，请使用 OptionItemsSetting.vue）
-->
<template>
  <div class="option-item-settings-panel">
    <div v-if="selectedWidget.type != 'zoning-unit-tree'"
      class="option-items-mode-radio">
      <el-radio-group size="small"
        v-model="optionConfig.mode"
        @change="optionModeChange">
        <el-radio-button v-for="(item) in Object.values(MODE_TYPE_CONS)"
          :key="item.value"
          :value="item.value">
          {{ item.name }}
        </el-radio-button>
      </el-radio-group>
    </div>
    <div v-if="selectedWidget.type != 'zoning-unit-tree'"
      class="
      option-items-mode-content">
      <div class="option-mode-item static-mode-item"
        v-if="optionConfig.mode === MODE_TYPE_CONS.STATIC.value">
        <div v-if="selectedWidget.type === 'select'">
          <el-select size="small"
            style="width: 100%;"
            clearable
            placeholder="请设置默认值"
            v-model="optionModel.defaultValue">
            <el-option v-for="item in optionModel.optionItemsSelect"
              :key="item[optionConfig.fieldNames.value]"
              :label="item[optionConfig.fieldNames.label] || ''"
              :value="item[optionConfig.fieldNames.value] || ''">
            </el-option>
          </el-select>
        </div>
        <div v-if="selectedWidget.type === 'tree-select'">
          <el-tree-select clearable
            style="width: 100%;"
            placeholder="请设置默认值"
            v-model="optionModel.defaultValue"
            :data="optionModel.optionItemsSelect"
            :props="{
              label: optionConfig.fieldNames.label,
              children: optionConfig.fieldNames.children
            }"
            :value-key="optionConfig.fieldNames.value"
            :check-strictly="true" />
        </div>
        <el-button link
          type="primary"
          @click="editSelectOptions">配置选项</el-button>
      </div>
      <div class="option-mode-item enums-mode-item"
        v-if="optionConfig.mode === MODE_TYPE_CONS.DICT.value">
        <el-divider class="mode-item-divider"><span class="title">字典选择</span></el-divider>
        <el-form class="select-options-form"
          size="small"
          label-position="left"
          label-width="80px"
          :model="optionConfig.dictConfig">
          <el-form-item label="字典类型">
            <el-select v-model="optionConfig.dictConfig.dictType"
              style="width: 100%;"
              size="small"
              placeholder="请选择"
              @change="dictTypeChange">
              <el-option v-for="(item, key, index) in DICT_TYPE_CONS"
                :key="item.value"
                :label="item.name"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="字典名称">
            <el-input type="text"
              readonly
              placeholder="请选择"
              v-model="optionConfig.dictConfig.dictName"
              :title="optionConfig.dictConfig.dictName">
              <template #append>
                <el-button type="primary"
                  class="input-select-btn"
                  @click="selectDictInfo()"
                  style="color: #fff; background-color: #409eff; border-top-left-radius: 0; border-bottom-left-radius: 0;">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="字典参数">
            <el-button type="info"
              icon="el-icon-edit"
              plain
              round
              @click="editDictParams">编写参数</el-button>
          </el-form-item>
          <el-form-item label="默认选中">
            <el-input type="text"
              placeholder="请输入"
              v-model="optionModel.defaultValue"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="option-mode-item serve-mode-item"
        v-if="optionConfig.mode === MODE_TYPE_CONS.SERVE.value">
        <el-divider class="mode-item-divider"><span class="title">请求配置</span></el-divider>
        <el-form class="select-options-form"
          size="small"
          label-position="left"
          label-width="80px"
          :model="optionConfig.serveConfig">
          <el-form-item label="请求地址">
            <el-input type="text"
              placeholder="请输入"
              v-model="optionConfig.serveConfig.url">
            </el-input>
          </el-form-item>
          <el-form-item label="请求方式">
            <el-select v-model="optionConfig.serveConfig.method"
              style="width: 100%;"
              size="small"
              placeholder="请选择">
              <el-option v-for="(item) in SERVE_METHOD_CONS"
                :key="item.value"
                :label="item.name"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="参数类型">
            <el-radio-group size="small"
              v-model="optionConfig.serveConfig.paramsType">
              <el-radio-button v-for="(item) in Object.values(SERVE_PARAMS_TYPE_CONS)"
                :key="item.value"
                :value="item.value">
                {{ item.name }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="请求参数">
            <el-button type="info"
              icon="el-icon-edit"
              plain
              round
              @click="editServeParams">编写参数</el-button>
          </el-form-item>
          <el-form-item label="默认选中">
            <el-input type="text"
              placeholder="请输入"
              v-model="optionModel.defaultValue"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="option-items-mode-field">
      <el-divider class="option-config-divider"><span class="title">字段替换</span></el-divider>
      <div v-for="(value, key, index) in optionConfig.fieldNames"
        style="margin-bottom: 10px;">
        <el-input v-model="optionConfig.fieldNames[key]">
          <template #prepend>
            <span style="width: 42px;">{{ key }}</span>
          </template>
        </el-input>
      </div>
    </div>
    <div v-if="editOptionItemFlag" >
      <vxe-modal :="dialogAttrs"
        title="配置数据"
        v-model="editOptionItemFlag">
        <AceCodeEditor :mode="'javascript'"
          v-model="selectOptionsCode"></AceCodeEditor>
        <template #footer>
          <div class="dialog-footer">
            <el-button size="default"
              type="primary"
              @click="saveSelectOptions">保存</el-button>
            <el-button size="default"
              type="primary"
              @click="editOptionItemFlag = false">取消</el-button>
          </div>
        </template>
      </vxe-modal>
    </div>
    <div v-if="editDictParamsFlag" >
      <vxe-modal :="dialogAttrs"
        title="编写参数"
        v-model="editDictParamsFlag">
        <div style="padding: 0 12px;">
          <span>数据类型：</span>
          <el-switch v-model="dictParamsIsFunc"
            size="default"
            inline-prompt
            style="--el-switch-on-color: #409eff; --el-switch-off-color: #13ce66;"
            active-text="方法"
            inactive-text="文本" />
        </div>
        <el-alert style="padding: 0;"
          type="info"
          v-show="dictParamsIsFunc"
          :closable="false"
          title="function () {"></el-alert>
        <AceCodeEditor :mode="dictParamsIsFunc ? 'javascript' : 'text'"
          v-model="editDictParamsCode"></AceCodeEditor>
        <el-alert style="padding: 0;"
          type="info"
          v-show="dictParamsIsFunc"
          :closable="false"
          title="}"></el-alert>
        <template #footer>
          <div class="dialog-footer">
            <el-button size="default"
              type="primary"
              @click="saveDictParams">保存</el-button>
            <el-button size="default"
              type="primary"
              @click="editDictParamsFlag = false">取消</el-button>
          </div>
        </template>
      </vxe-modal>
    </div>
    <div v-if="editServeParamsFlag" >
      <vxe-modal :="dialogAttrs"
        title="编写参数"
        v-model="editServeParamsFlag">
        <div class="serve-params-dialog-toolar">
          <div class="dialog-toolar-item">
            <div>数据类型：</div>
            <el-switch v-model="serveParamsIsFunc"
              size="default"
              inline-prompt
              style="--el-switch-on-color: #409eff; --el-switch-off-color: #13ce66;"
              active-text="方法"
              inactive-text="对象" />
          </div>
        </div>
        <el-alert style="padding: 0;"
          type="info"
          v-show="serveParamsIsFunc"
          :closable="false"
          title="function () {"></el-alert>
        <AceCodeEditor mode="javascript"
          v-model="editServeParamsCode"></AceCodeEditor>
        <el-alert style="padding: 0;"
          type="info"
          v-show="serveParamsIsFunc"
          :closable="false"
          title="}"></el-alert>
        <template #footer>
          <div class="dialog-footer">
            <el-button size="default"
              type="primary"
              @click="saveServeParams">保存</el-button>
            <el-button size="default"
              type="primary"
              @click="editServeParamsFlag = false">取消</el-button>
          </div>
        </template>
      </vxe-modal>
    </div>
    <DictSelectDialog ref="dictSelectDialogRef"
      :dictName="optionConfig.dictConfig.dictName"
      :dictType="optionConfig.dictConfig.dictType"
      :enumsDataPools="enumsDataPools"
      @confirm="setDictInfo">
    </DictSelectDialog>
  </div>
</template>

<!-- 下拉选项的配置 -->
<script setup name="SelectOptionItemsSetting">

import { baseAttrs } from '@/components/dialogs/cfg/base-cofig.js'
import { AceCodeEditor } from '@/components/vf-editor'
import { DictSelectDialog } from '@/components/dialogs'

import XEUtils from 'xe-utils'
import { i18n } from "@/utils/i18n"

import { VfMessage } from '@/utils/vf-utils'
import { computed, ref, inject, reactive } from 'vue'
import {
  MODE_TYPE_CONS,
  DICT_TYPE_CONS,
  DICT_CONFIG_CONS,
  SERVE_CONFIG_CONS,
  SERVE_METHOD_CONS,
  SERVE_PARAMS_TYPE_CONS,
  OPTION_FIELD_NAMES_CONS,
} from '@/constant/constant-options'

// props
const props = defineProps({
  designer: { type: Object },
  optionModel: { type: Object },
  selectedWidget: { type: Object }
})

// inject
const enumsDataPools = inject('enumsDataPools')

const dialogAttrs = reactive({
  ...baseAttrs,
  className: `${baseAttrs.className} vf-setting-dialog`
})

// ----- 数据模式相关
// 数据模式切换
const optionModeChange = () => {
  // 重置选中项
  props.optionModel.defaultValue = undefined
  // 重置静态数据
  props.optionModel.optionItemsSelect = []
  // 还原已修改选项对应字段信息
  const { type: widgetType } = props.selectedWidget
  optionConfig.value.fieldNames = XEUtils.clone(OPTION_FIELD_NAMES_CONS[widgetType].common, true)
  // 重置字典选项配置
  optionConfig.value.dictConfig = XEUtils.clone(DICT_CONFIG_CONS, true)
  // 重置动态选项配置
  optionConfig.value.serveConfig = XEUtils.clone(SERVE_CONFIG_CONS, true)
}
// 计算属性-optionConfig
const optionConfig = computed({
  get() {
    const resultConfig = props.selectedWidget.options.optionConfig
    if (!resultConfig.serveConfig) resultConfig.serveConfig = XEUtils.clone(SERVE_CONFIG_CONS, true)
    return resultConfig
  },
  set(newValue) {
    props.selectedWidget.options.optionConfig = newValue
  }
})

// ----- 导入静态数据相关
const editOptionItemFlag = ref(false)
const selectOptionsCode = ref('')
const editSelectOptions = () => {
  editOptionItemFlag.value = true
  selectOptionsCode.value = JSON.stringify(props.optionModel.optionItemsSelect, null, '  ')
}
const saveSelectOptions = () => {
  try {
    const newOptions = JSON.parse(selectOptionsCode.value)
    props.optionModel.optionItemsSelect = newOptions
    editOptionItemFlag.value = false
  } catch (ex) {
    VfMessage.error(i18n.$st('designer.hint.invalidOptionsData'))
  }
}

// ----- 字典数据相关
const dictSelectDialogRef = ref()
const dictTypeChange = (value) => {
  // 重置选中项
  props.optionModel.defaultValue = undefined
  // 重置静态数据
  props.optionModel.optionItemsSelect = []
  // 还原已修改选项对应字段信息
  const { type: widgetType } = props.selectedWidget
  optionConfig.value.fieldNames = XEUtils.clone(OPTION_FIELD_NAMES_CONS[widgetType][value], true)
  // 重置字典选项配置
  optionConfig.value.dictConfig.dictName = ''
  optionConfig.value.dictConfig.dictParams = ''
}
const selectDictInfo = () => {
  dictSelectDialogRef.value.handleOpen()
}
const setDictInfo = (row) => {
  optionConfig.value.dictConfig.dictName = row.value
}

// ----- 编写参数信息
const dictParamsIsFunc = ref(false)
const editDictParamsFlag = ref(false)
const editDictParamsCode = ref('')
const editDictParams = () => {
  editDictParamsCode.value = ''
  editDictParamsFlag.value = true
  const { dictParams } = optionConfig.value.dictConfig
  dictParamsIsFunc.value = false
  if (dictParams) {
    if (dictParams.startsWith(`func:`)) {
      dictParamsIsFunc.value = true
      const editParams = dictParams.replace(`func:`, '')
      editDictParamsCode.value = editParams
    } else {
      editDictParamsCode.value = dictParams
    }
  }
}
const saveDictParams = () => {
  editDictParamsFlag.value = false
  let resultParams = ''
  if (dictParamsIsFunc.value) {
    resultParams = `func:${editDictParamsCode.value}`
  } else {
    resultParams = editDictParamsCode.value
  }
  optionConfig.value.dictConfig.dictParams = XEUtils.clone(resultParams, true)
}

// ----- 编写请求参数
const serveParamsIsFunc = ref(false)
const editServeParamsFlag = ref(false)
const editServeParamsCode = ref('')
const editServeParams = () => {
  editServeParamsCode.value = ''
  editServeParamsFlag.value = true
  const { params } = optionConfig.value.serveConfig
  if (params && XEUtils.isObject(params)) {
    serveParamsIsFunc.value = false
    editServeParamsCode.value = JSON.stringify(params, null, '  ')
  }
  if (params && XEUtils.isString(params)) {
    const editParams = params.replace(`func:`, '')
    serveParamsIsFunc.value = true
    editServeParamsCode.value = editParams
  }
}
const saveServeParams = () => {
  let resultParams = ''
  if (serveParamsIsFunc.value) {
    resultParams = `func:${editServeParamsCode.value}`
    optionConfig.value.serveConfig.params = resultParams
    editServeParamsFlag.value = false
  } else {
    try {
      resultParams = editServeParamsCode.value
      optionConfig.value.serveConfig.params = JSON.parse(resultParams)
      editServeParamsFlag.value = false
    } catch (err) {
      VfMessage.error('参数解析出错！')
    }
  }
}

</script>

<style lang="scss" scoped>
.option-item-settings-panel {
  width: 100%;
}
.option-items-mode-radio {
  width: 100%;
  text-align: center;
}
.option-mode-item {
  margin-top: 8px;
}
.mode-item-divider {
  margin: 0;
  margin-top: 15px;
  margin-bottom: 15px;
  .title {
    font-size: 12px;
  }
}
.select-options-form {
  :deep(.el-form-item) {
    margin-bottom: 5px;
  }
}
.serve-params-dialog-toolar {
  display: flex;
  .dialog-toolar-item {
    padding-left: 12px;
    margin-right: 8px;
    display: flex;
    align-items: center;
  }
}
</style>